import { FC } from "react";
import { Avatar, Dropdown, message as antMessage } from "antd";
import { PhoneOutlined } from "@ant-design/icons";
import type { MenuProps } from "antd";

// 表情映射，与 EmojiPicker 中的映射相对应
const emojiMapping: Record<string, string> = {
  // 表情脸部
  "[微笑]": "😊",
  "[大笑]": "😂",
  "[爱心眼]": "😍",
  "[亲亲]": "😘",
  "[难过]": "😢",
  "[大哭]": "😭",
  "[生气]": "😡",
  "[思考]": "🤔",
  "[睡觉]": "😴",
  "[抱抱]": "🤗",
  "[酷]": "😎",
  "[天使]": "😇",
  "[调皮]": "😜",
  "[馋]": "😋",
  "[惊吓]": "😱",
  "[无语]": "😒",

  // 手势
  "[赞]": "👍",
  "[踩]": "👎",
  "[招手]": "👋",
  "[感谢]": "🙏",
  "[胜利]": "✌️",
  "[OK]": "👌",
  "[鼓掌]": "👏",
  "[握手]": "🤝",

  // 符号和物品
  "[爱心]": "❤️",
  "[心碎]": "💔",
  "[闪亮爱心]": "💖",
  "[100分]": "💯",
  "[庆祝]": "🎉",
  "[礼物]": "🎁",
  "[幸运]": "🍀",
  "[玫瑰]": "🌹",
  "[太阳]": "🌞",
  "[月亮]": "🌙",
  "[星星]": "⭐",
  "[火]": "🔥",

  // 动物
  "[猫]": "🐱",
  "[狗]": "🐶",
  "[熊猫]": "🐼",
  "[猴子]": "🐵"
};

// 将消息文本中的表情代码转换为实际表情
const convertMessageToEmoji = (message: string) => {
  if (typeof message !== "string") return message;

  // 使用正则表达式匹配所有 [...] 格式的文本
  return message.replace(/\[([^\]]+)\]/g, match => {
    // 如果匹配的文本在表情映射中存在，则替换为对应的表情
    return emojiMapping[match] || match;
  });
};

export interface ChatItemProps {
  isMe: boolean;
  message: string;
  avatar: string;
  messagetype?: string;
  showTime?: boolean;
  time?: string;
  userName?: string;
  isGroupChat?: boolean;
  groupUserName?: string;
  messageId?: string | number;
  onRecallMessage?: (messageId: string | number) => void;
  messageStatus?: number;
  customStyle?: {
    myMessageBg?: string;
    friendMessageBg?: string;
    messageTextColor?: string;
    fontFamily?: string;
  };
}

const ChatItem: FC<ChatItemProps> = ({ 
  isMe, 
  message, 
  avatar, 
  messagetype, 
  showTime, 
  time, 
  userName, 
  isGroupChat, 
  groupUserName,
  messageId,
  onRecallMessage,
  messageStatus,
  customStyle = {}
}) => {

  // 如果消息已撤回(messageStatus为0)，则不显示
  if (messageStatus === 0) {
    return null;
  }

  // 获取样式，使用自定义样式或默认样式
  const myBgColor = customStyle.myMessageBg || "#95ec69";
  const friendBgColor = customStyle.friendMessageBg || "#a0cfff";
  const textColor = customStyle.messageTextColor || "#303133";
  const fontFamily = customStyle.fontFamily || "inherit";

  // 转换消息文本中的表情代码
  const displayMessage = convertMessageToEmoji(message.toString());
  
  // 处理撤回消息
  const handleRecallMessage = () => {
    if (messageId && onRecallMessage) {
      console.log(messageId, "messageId");
      onRecallMessage(messageId);
    } else {
      antMessage.error("无法撤回消息");
    }
  };
  
  // 为我发送的消息创建右键菜单
  const items: MenuProps["items"] = [
    {
      key: "1",
      label: "撤回消息",
      onClick: handleRecallMessage,
    },
  ];

  // 通话记录消息（messageType 为 "call"），居中并设置文本颜色为蓝色
  if (messagetype === "call") {
    return (
      <li 
        className="listitem my-[15px] flex w-full relative z-10 items-start list-none justify-center"
        style={{ fontFamily }}
      >
        <div className="text-sm text-blue-500 whitespace-pre-wrap flex items-center">
          <PhoneOutlined className="mr-2" />
          {displayMessage}
        </div>
      </li>
    );
  }

  // 普通用户消息
  return (
    <li 
      className="listitem my-[15px] flex w-full relative z-10 items-start list-none"
      style={{ fontFamily }}
    >
      {!isMe && (
        <div className="flex flex-col">
          {isGroupChat && !isMe && (
            <span className="text-xs text-gray-500 mb-1 ml-9 truncate">
              {groupUserName || userName || "用户"}
            </span>
          )}
          <div className="flex items-start">
            <Avatar
              src={avatar}
              className="h-7 w-7 min-w-7 bg-[#a0cfff] text-xs mt-1"
            />
            <div
              className="ml-2 box-border max-w-[85%] rounded-md px-[10px] py-[7px] break-words"
              style={{ 
                background: friendBgColor,
                color: textColor
              }}
            >
              {messagetype === "img" ? (
                <img src={message} className="my-0 mr-0 h-30 w-30"></img>
              ) : (
                // 对于其他类型的用户消息（如文本），正常显示
                <div className="text-sm whitespace-pre-wrap">{displayMessage}</div>
              )}
            </div>
          </div>
        </div>
      )}
      
      {isMe && (
        <div className="flex flex-col w-full">
          {isGroupChat && isMe && (
            <span className="text-xs text-gray-500 mb-1 self-end mr-9 truncate">
              我
            </span>
          )}
          <div className="flex items-start justify-end w-full">
            <Dropdown menu={{ items }} trigger={["contextMenu"]} disabled={!messageId || messagetype === "call"}>
              <div
                className="mr-2 box-border max-w-[85%] rounded-md px-[10px] py-[7px] break-words"
                style={{ 
                  background: myBgColor,
                  color: textColor
                }}
              >
                {messagetype === "img" ? (
                  <img src={message} className="my-0 mr-0 h-30 w-30"></img>
                ) : (
                  // 对于其他类型的用户消息（如文本），正常显示
                  <div className="text-sm whitespace-pre-wrap">{displayMessage}</div>
                )}
              </div>
            </Dropdown>
            <Avatar
              src={avatar}
              className="h-7 w-7 min-w-7 text-xs mt-1"
              style={{ background: myBgColor }}
            />
          </div>
        </div>
      )}
      
      {showTime && time && (
        <div className={`absolute ${isMe ? "right-10" : "left-10"} top-[-15px] text-[10px] text-gray-400`}>
          {time}
        </div>
      )}
    </li>
  );
};

export default ChatItem;
